package com.wtb.javatool.action;

import com.fy.wetoband.tool.Tool;
import com.fy.wetoband.utils.RequestUtil;
import com.wtb.javatool.common.PageResult;
import com.wtb.javatool.common.Result;
import com.wtb.javatool.entity.*;
import com.wtb.javatool.service.*;
import com.wtb.javatool.vo.*;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Scope;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

import static org.springframework.beans.factory.config.ConfigurableBeanFactory.SCOPE_PROTOTYPE;

@Slf4j
@Api(value = "javatool", description = "java工具示例")
@Scope(SCOPE_PROTOTYPE) //务必使用多实例模式
@ComponentScan("com.wtb.javatool")
public class JavaToolDemoAction extends Tool {

    @Autowired
    private IDishService dishService;
    @Autowired
    private ISelfBuiltDatabaseService selfBuiltDatabaseService;
    @Autowired
    private IPublicDatabaseService publicDatabaseService;
    @Autowired
    private ILogService logService;
    @Autowired
    private IStuApplyService stuApplyService;
    @Autowired
    private ITeacherApplyService teacherApplyService;

    @Action
    @ApiOperation(value = "添加菜品", httpMethod = "POST", notes = "添加菜品信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", dataType = "string", value = "菜品名称", required = true),
            @ApiImplicitParam(name = "price", dataType = "string", value = "菜品价格", required = true, defaultValue = "1"),
            @ApiImplicitParam(name = "desc", dataType = "string", value = "菜品描述", required = false)
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "添加菜品成功", response = Result.class)
    })
    public Result<String> saveDish(HttpServletRequest request, HttpServletResponse response) {

        String name = RequestUtil.getStringParameter(request, "name");
        String price = RequestUtil.getStringParameter(request, "price");
        String desc = RequestUtil.getStringParameter(request, "desc");

        Dish dish = new Dish(name, new BigDecimal(price), desc);

        final Integer save = dishService.save(dish);
        if(save <= 0){
            return Result.error("添加菜品失败");
        }

        return Result.success("添加菜品成功");
    }

    @Action
    public Result<String> helloworld(HttpServletRequest request, HttpServletResponse response) {
        return Result.success("广州城市理工你好");
    }

    @Action
    @ApiOperation(value = "修改菜品", httpMethod = "POST", notes = "修改菜品信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", dataType = "string", value = "菜品ID", required = true),
            @ApiImplicitParam(name = "name", dataType = "string", value = "菜品名称", required = true),
            @ApiImplicitParam(name = "price", dataType = "string", value = "菜品价格", required = true, defaultValue = "1"),
            @ApiImplicitParam(name = "desc", dataType = "string", value = "菜品描述", required = false)
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "修改菜品成功", response = Result.class)
    })
    public Result<String> updateDish(HttpServletRequest request, HttpServletResponse response) {

        Long dishId = RequestUtil.getLongParameter(request, "dishId");
        String name = RequestUtil.getStringParameter(request, "name");
        String price = RequestUtil.getStringParameter(request, "price");
        String desc = RequestUtil.getStringParameter(request, "desc");

        Dish dish = new Dish(name, new BigDecimal(price), desc);
        dish.setId(dishId);

        final Integer update = dishService.update(dish);
        if (update<=0){
            return Result.error("修改菜品失败");
        }
        return Result.success("修改菜品成功");
    }


    @Action
    @ApiOperation(value = "列出所有菜品", httpMethod = "GET", notes = "列出所有菜品")
    @ApiResponses({
            @ApiResponse(code = 200, message = "成功", response = Result.class)
    })
    public Result<List<DishDto>> listAll(HttpServletRequest request, HttpServletResponse response) {
        List<Dish> dishes = dishService.listAll();
        if(dishes == null || dishes.size() == 0){
            return Result.success(null);
        }

        List<DishDto> list = dishes.stream().map(new Function<Dish, DishDto>() {
            @Override
            public DishDto apply(Dish dish) {
                DishDto dto = new DishDto();
                BeanUtils.copyProperties(dish, dto);
                return dto;
            }
        }).collect(Collectors.toList());
        return Result.success(list);
    }

    @Action
    @ApiOperation(value = "删除菜品", httpMethod = "POST", notes = "删除菜品信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", dataType = "long", value = "菜品ID", required = true),
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "添加菜品成功", response = Result.class)
    })
    public Result<String> deleteDish(HttpServletRequest request, HttpServletResponse response) {

        Long dishId = RequestUtil.getLongParameter(request, "dishId");

        final Integer delete = dishService.delete(dishId);
        if (delete<=0){
            return Result.error("删除菜品失败");
        }
        return Result.success("删除菜品成功");
    }

    @Action
    @ApiOperation(value = "自建数据库申请提交接口", httpMethod = "POST", notes = "学生向教师提交自建数据库申请，教师向管理员发起建立数据库的请求")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "studentId", dataType = "string", value = "学生编号", required = true),
            @ApiImplicitParam(name = "courseId", dataType = "string", value = "课程编号", required = true),
            @ApiImplicitParam(name = "description", dataType = "string", value = "数据库描述", required = true),
            @ApiImplicitParam(name = "approverId", dataType = "string", value = "审批人编号", required = true)
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "申请提交成功", response = Result.class)
    })
    public Result<String> applyByCourse(HttpServletRequest request, HttpServletResponse response) {
        log.info("添加申请");

        String studentId = RequestUtil.getStringParameter(request, "studentId");
        String courseId = RequestUtil.getStringParameter(request, "courseId");
        String description = RequestUtil.getStringParameter(request, "description");
        String approverId = RequestUtil.getStringParameter(request, "approverId");

        SelfBuiltDatabase selfBuiltDatabase = new SelfBuiltDatabase(studentId,courseId,description,approverId);
        selfBuiltDatabase.setAuthorizerId(studentId);
        selfBuiltDatabase.setDatabaseName("1");

        final Integer applyByCourse = selfBuiltDatabaseService.applyByCourse(selfBuiltDatabase);
        log.info("跑通方法");
        if (applyByCourse<=0){
            return Result.error("申请提交失败");
        }
        return Result.success("申请提交成功");
    }

    @Action
    @ApiOperation(value = "教师端教师给单个学生授权", httpMethod = "POST", notes = "学生授权")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", dataType = "int", value = "id",  required = true),
            @ApiImplicitParam(name = "authType", dataType = "string", value = "授权类型",  required = true),
            @ApiImplicitParam(name = "accessDuration", dataType = "int", value = "访问时长",  required = true),
            @ApiImplicitParam(name = "description", dataType = "string", value = "授权备注",  required = false),

    })
    @ApiResponses({
            @ApiResponse(code = 200,message = "学生授权成功", response = Result.class)
    })
    public Result<String> doAuthorize(HttpServletRequest request, HttpServletResponse response) {
        int id =Integer.parseInt( request.getParameter("id"));
        String auth_type = request.getParameter("authType");
        int accessDuration = Integer.parseInt(request.getParameter("accessDuration"));
        String description = request.getParameter("description");
        StuAuthDto stuAuthDTO = new StuAuthDto();
        stuAuthDTO.setId(id);
        stuAuthDTO.setAuth_type(auth_type);
        stuAuthDTO.setAccessDuration(accessDuration);
        stuAuthDTO.setDescription(description);
        stuApplyService.doAuthorize(stuAuthDTO);
        return Result.success("学生授权成功");
    }


    @Action
    @ApiOperation(value = "教师端教师批量给学生授权", httpMethod = "POST", notes = "对学生进行批量授权")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", dataType = "string", value = "学生ID列表（逗号分隔）", required = true),
            @ApiImplicitParam(name = "authType", dataType = "string", value = "授权类型", required = true),
            @ApiImplicitParam(name = "accessDuration", dataType = "int", value = "访问时长（单位天）", required = true),
            @ApiImplicitParam(name = "description", dataType = "string", value = "授权备注", required = false)
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "批量授权成功", response = Result.class)
    })
    public Result<String> doBatchAuthorize(HttpServletRequest request, HttpServletResponse response) {
        String idsStr = request.getParameter("ids");
        String authType = request.getParameter("authType");
        int accessDuration = Integer.parseInt(request.getParameter("accessDuration"));
        String description = request.getParameter("description");

        if (idsStr == null || idsStr.trim().isEmpty()) {
            return Result.error("学生ID不能为空");
        }

        String[] idArray = idsStr.split(",");
        int successCount = 0;

        for (String idStr : idArray) {
            try {
                int id = Integer.parseInt(idStr.trim());
                StuAuthDto stuAuthDTO = new StuAuthDto();
                stuAuthDTO.setId(id);
                stuAuthDTO.setAuth_type(authType);
                stuAuthDTO.setAccessDuration(accessDuration);
                stuAuthDTO.setDescription(description);

                stuApplyService.doAuthorize(stuAuthDTO);
            } catch (NumberFormatException e) {
                log.error("无效的学生ID: {}", idStr, e);
                continue; // 跳过非法ID
            }
        }

        return Result.success("成功批量授权 " );
    }

    @Action
    @ApiOperation(value = "自建数据库申请状态查询接口", httpMethod = "GET", notes = "学生可通过系统界面实时跟踪自建数据库申请的审核状态，了解进展")
    @ApiResponses({
            @ApiResponse(code = 200, message = "查询成功", response = Result.class)
    })
    public Result<List<SelfBuiltDatabaseDto>> status(HttpServletRequest request, HttpServletResponse response) {
        List<SelfBuiltDatabase> selfBuiltDatabases = selfBuiltDatabaseService.status();
        if(selfBuiltDatabases == null || selfBuiltDatabases.size() == 0){
            return Result.success(null);
        }
        List<SelfBuiltDatabaseDto> list = selfBuiltDatabases.stream().map(new Function<SelfBuiltDatabase, SelfBuiltDatabaseDto>() {
            @Override
            public SelfBuiltDatabaseDto apply(SelfBuiltDatabase selfBuiltDatabase) {
                SelfBuiltDatabaseDto dto = new SelfBuiltDatabaseDto();
                BeanUtils.copyProperties(selfBuiltDatabase, dto);
                return dto;
            }
        }).collect(Collectors.toList());
        return Result.success(list);
    }

    @Action
    @ApiOperation(value = "学生端公共数据库联合查询申请接口", httpMethod = "POST", notes = "学生在系统中同时选择数据表，输入查询条件进行联合查询申请操作")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "studentId", dataType = "string", value = "学号", required = true),
            @ApiImplicitParam(name = "databaseName", dataType = "string", value = "公共数据库编号数组", required = true),
            @ApiImplicitParam(name = "applyAim", dataType = "string", value = "申请目的", required = true),
            @ApiImplicitParam(name = "approverId", dataType = "string", value = "审批员（老师）", required = true)
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "申请成功", response = Result.class)
    })
    public Result<String> publicDatabaseApplication(HttpServletRequest request, HttpServletResponse response) {

        String studentId = RequestUtil.getStringParameter(request, "studentId");
        String databaseName = RequestUtil.getStringParameter(request, "databaseName");
        String applyAim = RequestUtil.getStringParameter(request, "applyAim");
        String approverId = RequestUtil.getStringParameter(request, "approverId");

        PublicDatabase publicDatabase = new PublicDatabase(studentId,databaseName,applyAim,approverId);

        final Integer publicDatabaseApplication = publicDatabaseService.application(publicDatabase);
        if (publicDatabaseApplication<=0){
            return Result.error("申请提交失败");
        }
        return Result.success("申请提交成功");
    }

    @Action
    @ApiOperation(value = "学生端公共数据库申请状态查询接口", httpMethod = "GET", notes = "学生可通过系统界面实时跟踪公共数据库申请的审核状态，了解进展")
    @ApiResponses({
            @ApiResponse(code = 200, message = "查询成功", response = Result.class)
    })
    public Result<List<PublicDatabaseDto>> publicDatabaseQuery(HttpServletRequest request, HttpServletResponse response){
        List<PublicDatabase> publicDatabases = publicDatabaseService.query();
        if(publicDatabases == null || publicDatabases.size() == 0){
            return Result.success(null);
        }
        List<PublicDatabaseDto> list = publicDatabases.stream().map(new Function<PublicDatabase, PublicDatabaseDto>() {
            @Override
            public PublicDatabaseDto apply(PublicDatabase publicDatabase) {
                PublicDatabaseDto dto = new PublicDatabaseDto();
                BeanUtils.copyProperties(publicDatabase, dto);
                return dto;
            }
        }).collect(Collectors.toList());
        return Result.success(list);
    }
    @Action
    @ApiOperation(value = "table_meta表查询接口", httpMethod = "GET", notes = "将table_meta表的数据查询返回前端供选择")
    @ApiResponses({
            @ApiResponse(code = 200, message = "查询成功", response = Result.class)
    })
    public Result<List<TableMetaDto>> tableMeta(HttpServletRequest request, HttpServletResponse response) {
        List<TableMeta> tableMeta = publicDatabaseService.tableMeta();
        if (tableMeta == null || tableMeta.size() == 0){
            return Result.success(null);
        }
        List<TableMetaDto> list = tableMeta.stream().map(new Function<TableMeta, TableMetaDto>() {
            @Override
            public TableMetaDto apply(TableMeta tableMeta) {
                TableMetaDto dto = new TableMetaDto();
                BeanUtils.copyProperties(tableMeta, dto);
                return dto;
            }
        }).collect(Collectors.toList());
        return Result.success(list);
    }


    @Action
    @ApiOperation(value = "学生端学生自建数据库申请提交", httpMethod = "POST", notes = "学生向教师提交自建数据库申请")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", dataType = "string", value = "申请姓名", required = true),
            @ApiImplicitParam(name = "stu_sno", dataType = "string", value = "学生学号", required = true),
            @ApiImplicitParam(name = "courseName", dataType = "string", value = "课程名称", required = true),
            @ApiImplicitParam(name = "courseId", dataType = "string", value = "课程编号", required = true),
            @ApiImplicitParam(name = "remark", dataType = "string", value = "申请数据库描述", required = true),
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "申请提交成功", response = Result.class)
    })
    public Result<String> newApply(HttpServletRequest request, HttpServletResponse response) {
        log.info("添加申请");

        String name = RequestUtil.getStringParameter(request, "name");
        String stu_sno = RequestUtil.getStringParameter(request, "stu_sno");
        String courseName = RequestUtil.getStringParameter(request, "courseName");
        String courseId = RequestUtil.getStringParameter(request, "courseId");
        String description = RequestUtil.getStringParameter(request, "remark");

        StuApplyDto stuApplyDTO = new StuApplyDto();
        stuApplyDTO.setStu_name(name);
        stuApplyDTO.setStu_sno(stu_sno);
        stuApplyDTO.setCourse_name(courseName);
        stuApplyDTO.setCourse_id(courseId);
        stuApplyDTO.setRemark(description);
        stuApplyService.newApply(stuApplyDTO);
        return Result.success("申请提交成功");
    }



    @Action
    @ApiOperation(value = "(学生端/教师端)tci表查询接口", httpMethod = "GET", notes = "将tci表的数据查询返回前端供选择")
    @ApiResponses({
            @ApiResponse(code = 200, message = "查询成功", response = Result.class)
    })
    public Result<List<TciDto>> tci(HttpServletRequest request, HttpServletResponse response) {
        List<Tci> tci = selfBuiltDatabaseService.tci();
        if (tci == null || tci.size() == 0){
            return Result.success(null);
        }
        List<TciDto> list = tci.stream().map(new Function<Tci, TciDto>() {
            @Override
            public TciDto apply(Tci tci) {
                TciDto dto = new TciDto();
                BeanUtils.copyProperties(tci, dto);
                return dto;
            }
        }).collect(Collectors.toList());
        return Result.success(list);
    }


    @Action
    @ApiOperation(value = "管理员端分页查询日志", httpMethod = "GET", notes = "分页查询日志")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", dataType = "string", value = "管理员姓名",  required = false),
            @ApiImplicitParam(name = "startDate", dataType = "string", value = "开始日期",  required = false),
            @ApiImplicitParam(name = "endDate", dataType = "string", value = "结束日期",  required = false),
            @ApiImplicitParam(name = "pageNum", dataType = "Integer", value = "页码", required = true),
            @ApiImplicitParam(name = "pageSize", dataType = "Integer", value = "每页数量", required = true),
    })
    @ApiResponses({
            @ApiResponse(code = 200,message = "成功", response = Result.class)
    })
    public Result<PageResult> pageQuery(LogPageDto logPageDTO) {
        log.info("分页查询日志");
        PageResult pageResult = logService.pageQuery(logPageDTO);
        return Result.success(pageResult);
    }


    @Action
    @ApiOperation(value = "教师端分页查询学生自建数据库申请", httpMethod = "GET", notes = "分页查询学生自建数据库申请申请")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", dataType = "string", value = "管理员姓名",  required = false),
            @ApiImplicitParam(name = "pageNum", dataType = "int", value = "页码", required = true),
            @ApiImplicitParam(name = "pageSize", dataType = "int", value = "每页数量", required = true),
    })
    @ApiResponses({
            @ApiResponse(code = 200,message = "成功", response = Result.class)
    })
    public Result<PageResult> listAllPage1(HttpServletRequest request, HttpServletResponse response) {
        log.info("分页查询");
        int pageNum = Integer.parseInt(request.getParameter("pageNum"));
        int pageSize = Integer.parseInt(request.getParameter("pageSize"));
        String name = request.getParameter("name");
        PageResult pageResult = stuApplyService.stuApplypageQuery1(pageNum, pageSize, name) ;
        return Result.success(pageResult);
    }


    @Action
    @ApiOperation(value = "教师端分页查询教师处理后状态跟踪", httpMethod = "GET", notes = "分页查询教师授权或拒绝申请后的数据追踪")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", dataType = "string", value = "管理员姓名",  required = false),
            @ApiImplicitParam(name = "startDate", dataType = "string", value = "开始日期",  required = false),
            @ApiImplicitParam(name = "endDate", dataType = "string", value = "结束日期",  required = false),
            @ApiImplicitParam(name = "status", dataType = "string", value = "状态",  required = false),
            @ApiImplicitParam(name = "pageNum", dataType = "int", value = "页码", required = true),
            @ApiImplicitParam(name = "pageSize", dataType = "int", value = "每页数量", required = true),

    })
    @ApiResponses({
            @ApiResponse(code = 200,message = "成功", response = Result.class)
    })
    public Result<PageResult> listRecordAllPage(HttpServletRequest request, HttpServletResponse response) {
        int pageNum = Integer.parseInt(request.getParameter("pageNum"));
        int pageSize = Integer.parseInt(request.getParameter("pageSize"));
        String name = request.getParameter("name");
        String startDate = request.getParameter("startDate");
        String endDate = request.getParameter("endDate");
        String status = request.getParameter("status");
        LocalDateTime startDateTime = null;
        LocalDateTime endDateTime = null;
        // 定义日期格式（需与输入字符串格式一致）
        if (startDate != null) {
            // 定义日期时间格式
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            startDateTime = LocalDateTime.parse(startDate, formatter);
            endDateTime = LocalDateTime.parse(endDate,formatter);
        }
        StuApplyRecordPageDto stuApplyRecordPageDTO = new StuApplyRecordPageDto();
        stuApplyRecordPageDTO.setPageNum(pageNum);
        stuApplyRecordPageDTO.setPageSize(pageSize);
        stuApplyRecordPageDTO.setName(name);
        stuApplyRecordPageDTO.setStartTime(startDateTime);
        stuApplyRecordPageDTO.setEndTime(endDateTime);
        stuApplyRecordPageDTO.setStatus(status);
        PageResult pageResult = stuApplyService.stuApplyRecordpageQuery(stuApplyRecordPageDTO);
        return Result.success(pageResult);
    }




    @Action
    @ApiOperation(value = "管理端分页查询教师授权学生自建数据库申请后的数据", httpMethod = "GET", notes = "分页查询教师审批后的学生申请")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", dataType = "string", value = "学生姓名",  required = false),
            @ApiImplicitParam(name = "pageNum", dataType = "int", value = "页码", required = true),
            @ApiImplicitParam(name = "pageSize", dataType = "int", value = "每页数量", required = true),
    })
    @ApiResponses({
            @ApiResponse(code = 200,message = "成功", response = Result.class)
    })
    public Result<PageResult> listSelfBuildPage(HttpServletRequest request, HttpServletResponse response) {
        log.info("分页查询");
        int pageNum = Integer.parseInt(request.getParameter("pageNum"));
        int pageSize = Integer.parseInt(request.getParameter("pageSize"));
        String name = request.getParameter("name");
        PageResult pageResult = stuApplyService.stuApplypageQuery2(pageNum, pageSize, name) ;
        return Result.success(pageResult);
    }


    @Action
    @ApiOperation(value = "管理员端管理员同意自建数据库", httpMethod = "POST", notes = "管理员同意学生/教师自建数据库请求")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", dataType = "int", value = "id",  required = true)
    })
    @ApiResponses({
            @ApiResponse(code = 200,message = "授权成功", response = Result.class)
    })
    public Result<String> adminDoAuthorize(HttpServletRequest request, HttpServletResponse response) {
        int id =Integer.parseInt( request.getParameter("id"));
        stuApplyService.adminDoAuthorize(id);
        return Result.success("授权成功");
    }

    @Action
    @ApiOperation(value = "管理员拒绝自建数据库", httpMethod = "POST", notes = "管理员拒绝学生/教师自建数据库请求")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", dataType = "int", value = "id",  required = true)
    })
    @ApiResponses({
            @ApiResponse(code = 200,message = "管理员拒绝", response = Result.class)
    })
    public Result<String> adminReject(HttpServletRequest request, HttpServletResponse response) {
        int id =Integer.parseInt( request.getParameter("id"));
        stuApplyService.adminReject(id);
        return Result.success("拒绝成功");
    }


    @Action
    @ApiOperation(value = "学生端展示所有申请", httpMethod = "GET", notes = "展示所有学生申请数据")
    @ApiResponses({
            @ApiResponse(code = 200, message = "成功", response = Result.class)
    })
    public Result<List<StuApplyDetailDto>> stuListAll(HttpServletRequest request, HttpServletResponse response) {
        List<StuApplyDetailDto> stuApplyDetails = stuApplyService.stuListAll();
        if (stuApplyDetails == null || stuApplyDetails.size() == 0){
            return Result.success(null);
        }
        List<StuApplyDetailDto> list = stuApplyDetails.stream().map(new Function<StuApply, StuApplyDetailDto>() {
            @Override
            public StuApplyDetailDto apply(StuApply stuApply) {
                StuApplyDetailDto dto = new StuApplyDetailDto();
                BeanUtils.copyProperties(stuApply, dto);
                return dto;
            }
        }).collect(Collectors.toList());
        return Result.success(list);
    }


    @Action
    @ApiOperation(value = "教师端教师拒绝学生自建数据库申请", httpMethod = "POST", notes = "教师拒绝学生自建数据库申请")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", dataType = "int", value = "id",  required = true),
            @ApiImplicitParam(name = "rejectReason", dataType = "string", value = "拒绝原因",  required = false)
    })
    @ApiResponses({
            @ApiResponse(code = 200,message = "教师拒绝", response = Result.class)
    })
    public Result<String> teacherReject(HttpServletRequest request, HttpServletResponse response) {
        int id =Integer.parseInt( request.getParameter("id"));
        String reject_reason = request.getParameter("rejectReason");
        stuApplyService.teacherReject(id, reject_reason);
        return Result.success("拒绝成功");
    }

    @Action
    @ApiOperation(value = "教师端教师同意自建数据库", httpMethod = "POST", notes = "教师同意学生自建数据库")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", dataType = "int", value = "id",  required = true)
    })
    @ApiResponses({
            @ApiResponse(code = 200,message = "授权成功", response = Result.class)
    })
    public Result<String> teacherDoAuthorize(HttpServletRequest request, HttpServletResponse response) {
        int id =Integer.parseInt( request.getParameter("id"));
        stuApplyService.teacherDoAuthorize(id);
        return Result.success("授权成功");
    }

    @Action
    @ApiOperation(value = "教师端教师批量给学生授权", httpMethod = "POST", notes = "对学生进行批量授权")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", dataType = "string", value = "学生ID列表（逗号分隔）", required = true),
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "批量授权成功", response = Result.class)
    })
    public Result<String> teacherDoBatchAuthorize(HttpServletRequest request, HttpServletResponse response) {
        String idsStr = request.getParameter("ids");
        if (idsStr == null || idsStr.trim().isEmpty()) {
            return Result.error("学生ID不能为空");
        }

        String[] idArray = idsStr.split(",");
        int successCount = 0;

        for (String idStr : idArray) {
            try {
                int id = Integer.parseInt(idStr.trim());
                StuApply stuApply = new StuApply();
                stuApply.setId( id);
                stuApplyService.teacherDoAuthorize(id);
            } catch (NumberFormatException e) {
                log.error("无效的学生ID: {}", idStr, e);
                continue; // 跳过非法ID
            }
        }

        return Result.success("成功批量授权 " );
    }


    @Action
    @ApiOperation(value = "管理员端管理员批量授权", httpMethod = "POST", notes = "对学生/教师自建数据库申请进行批量授权")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", dataType = "string", value = "学生ID列表（逗号分隔）", required = true),
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "批量授权成功", response = Result.class)
    })
    public Result<String> adminDoBatchAuthorize(HttpServletRequest request, HttpServletResponse response) {
        String idsStr = request.getParameter("ids");
        if (idsStr == null || idsStr.trim().isEmpty()) {
            return Result.error("学生ID不能为空");
        }

        String[] idArray = idsStr.split(",");
        int successCount = 0;

        for (String idStr : idArray) {
            try {
                int id = Integer.parseInt(idStr.trim());
                StuApply stuApply = new StuApply();
                stuApply.setId( id);
                stuApplyService.adminDoAuthorize(id);
            } catch (NumberFormatException e) {
                log.error("无效的学生ID: {}", idStr, e);
            }
        }

        return Result.success("成功批量授权 " );
    }


    @Action
    @ApiOperation(value = "管理员管理员批量拒绝", httpMethod = "POST", notes = "对学生/教师自建数据库申请进行批量拒绝")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", dataType = "string", value = "学生ID列表（逗号分隔）", required = true),
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "批量拒绝成功", response = Result.class)
    })
    public Result<String> adminDoBatchReject(HttpServletRequest request, HttpServletResponse response) {
        String idsStr = request.getParameter("ids");
        if (idsStr == null || idsStr.trim().isEmpty()) {
            return Result.error("学生ID不能为空");
        }

        String[] idArray = idsStr.split(",");
        int successCount = 0;

        for (String idStr : idArray) {
            try {
                int id = Integer.parseInt(idStr.trim());
                StuApply stuApply = new StuApply();
                stuApply.setId( id);
                stuApplyService.adminReject( id);
            } catch (NumberFormatException e) {
                log.error("无效的学生ID: {}", idStr, e);
            }
        }

        return Result.success("成功批量拒绝 " );
    }


    @Action
    @ApiOperation(value = "教师端教师自建数据库申请提交", httpMethod = "POST", notes = "教师自建数据库申请提交")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", dataType = "string", value = "教师姓名", required = true),
            @ApiImplicitParam(name = "courseName", dataType = "string", value = "课程名称", required = true),
            @ApiImplicitParam(name = "courseId", dataType = "string", value = "课程编号", required = true),
            @ApiImplicitParam(name = "remark", dataType = "string", value = "申请数据库描述", required = true),
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "申请提交成功", response = Result.class)
    })
    public Result<String> teacherNewApply(HttpServletRequest request, HttpServletResponse response) {
        log.info("添加申请");

        String name = RequestUtil.getStringParameter(request, "name");
        String courseName = RequestUtil.getStringParameter(request, "courseName");
        String courseId = RequestUtil.getStringParameter(request, "courseId");
        String remark = RequestUtil.getStringParameter(request, "remark");

        TeacherApplyDto teacherApplyDTO = new TeacherApplyDto();
        teacherApplyDTO.setTeacher_name(name);
        teacherApplyDTO.setCourse_name(courseName);
        teacherApplyDTO.setCourse_id(courseId);
        teacherApplyDTO.setRemark(remark);
        teacherApplyService.newApply(teacherApplyDTO);
        return Result.success("申请提交成功");
    }

    @Action
    @ApiOperation(value = "教师端分页查询教师申请记录", httpMethod = "GET", notes = "分页查询教师申请记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "startDate", dataType = "string", value = "开始日期",  required = false),
            @ApiImplicitParam(name = "endDate", dataType = "string", value = "结束日期",  required = false),
            @ApiImplicitParam(name = "status", dataType = "string", value = "状态",  required = false),
            @ApiImplicitParam(name = "pageNum", dataType = "int", value = "页码", required = true),
            @ApiImplicitParam(name = "pageSize", dataType = "int", value = "每页数量", required = true),

    })
    @ApiResponses({
            @ApiResponse(code = 200,message = "成功", response = Result.class)
    })
    public Result<PageResult> teacherListRecordAllPage(HttpServletRequest request, HttpServletResponse response) {
        int pageNum = Integer.parseInt(request.getParameter("pageNum"));
        int pageSize = Integer.parseInt(request.getParameter("pageSize"));
        String startDate = request.getParameter("startDate");
        String endDate = request.getParameter("endDate");
        String status = request.getParameter("status");
        LocalDateTime startDateTime = null;
        LocalDateTime endDateTime = null;
        // 定义日期格式（需与输入字符串格式一致）
        if (startDate != null && !startDate.isEmpty()) {
            // 定义日期时间格式
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            startDateTime = LocalDateTime.parse(startDate, formatter);
            endDateTime = LocalDateTime.parse(endDate,formatter);
        }
        TeacherApplyRecordPageDto teacherApplyRecordPageDTO = new TeacherApplyRecordPageDto();
        teacherApplyRecordPageDTO.setPageNum(pageNum);
        teacherApplyRecordPageDTO.setPageSize(pageSize);
        teacherApplyRecordPageDTO.setStartTime(startDateTime);
        teacherApplyRecordPageDTO.setEndTime(endDateTime);
        teacherApplyRecordPageDTO.setStatus(status);
        PageResult pageResult = teacherApplyService.teacherApplyRecordpageQuery(teacherApplyRecordPageDTO);
        return Result.success(pageResult);
    }

    @Action
    @ApiOperation(value = "教师端教师帮学生自建数据库申请提交", httpMethod = "POST", notes = "教师帮学生自建数据库")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "stu_sno", dataType = "string", value = "学生学号", required = true),
            @ApiImplicitParam(name = "courseName", dataType = "string", value = "课程名称", required = true),
            @ApiImplicitParam(name = "courseId", dataType = "string", value = "课程编号", required = true),
            @ApiImplicitParam(name = "remark", dataType = "string", value = "申请数据库描述", required = true),
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "申请提交成功", response = Result.class)
    })
    public Result<String> teacherStuApply(HttpServletRequest request, HttpServletResponse response) {
        log.info("添加申请");
        String stu_sno = RequestUtil.getStringParameter(request, "stu_sno");
        String courseName = RequestUtil.getStringParameter(request, "courseName");
        String courseId = RequestUtil.getStringParameter(request, "courseId");
        String description = RequestUtil.getStringParameter(request, "remark");

        StuApplyDto stuApplyDTO = new StuApplyDto();
        stuApplyDTO.setStu_sno(stu_sno);
        stuApplyDTO.setCourse_name(courseName);
        stuApplyDTO.setCourse_id(courseId);
        stuApplyDTO.setRemark(description);
        stuApplyService.techerStunewApply(stuApplyDTO);
        return Result.success("申请提交成功");
    }

    @Action
    @ApiOperation(value = "管理员端分页查询教师自建数据库申请", httpMethod = "GET", notes = "分页查询教师自建数据库申请")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", dataType = "string", value = "管理员姓名",  required = false),
            @ApiImplicitParam(name = "pageNum", dataType = "int", value = "页码", required = true),
            @ApiImplicitParam(name = "pageSize", dataType = "int", value = "每页数量", required = true),
    })
    @ApiResponses({
            @ApiResponse(code = 200,message = "成功", response = Result.class)
    })
    public Result<PageResult> teacherListSelfBuildPage(HttpServletRequest request, HttpServletResponse response) {
        log.info("分页查询");
        int pageNum = Integer.parseInt(request.getParameter("pageNum"));
        int pageSize = Integer.parseInt(request.getParameter("pageSize"));
        String name = request.getParameter("name");
        PageResult pageResult = teacherApplyService.teacherListPage(pageNum, pageSize, name);
        return Result.success(pageResult);
    }

}